/**
 * 固定资产管理系统 - 增强仪表板组件
 * 基于配色规范和模块化架构
 */

class AssetDashboard {
    constructor() {
        this.colors = {
            primary: '#1e3a8a',
            secondary: '#64748b', 
            success: '#059669',
            warning: '#d97706',
            danger: '#dc2626',
            info: '#0284c7'
        };
        
        this.realTimeData = {
            assets: { total: 240, active: 189, idle: 45, maintenance: 6 },
            departments: { count: 8, mostActive: 'IT部门' },
            value: { total: 11000000, thisMonth: 850000 },
            alerts: []
        };
        
        this.init();
    }

    // 在资产日志/模态上下文中抑制交互与动画，避免闪烁
    isSuppressedContext() {
        try {
            return (
                document.body.classList.contains('modal-open') ||
                !!document.querySelector('.modal.show') ||
                !!document.querySelector('#assetLogsContainer') ||
                !!document.querySelector('.asset-logs') ||
                !!document.querySelector('.related-logs')
            );
        } catch (e) { return false; }
    }

    init() {
        console.log('🏢 初始化增强仪表板...');
        this.createDashboardPanels();
        this.startRealTimeUpdates();
        this.initializeInteractions();
    }

    createDashboardPanels() {
        this.createAssetOverviewPanel();
        this.createDepartmentInsightsPanel(); 
        this.createMaintenanceAnalyticsPanel();
        this.createFinancialSummaryPanel();
        this.createAlertsCenterPanel();
    }

    createAssetOverviewPanel() {
        const panel = this.createPanel('asset-overview-panel', '📊 资产总览', 'primary');
        
        const content = `
            <div class="dashboard-grid">
                <div class="metric-card">
                    <div class="metric-icon" style="background: linear-gradient(135deg, ${this.colors.primary}, ${this.colors.info});">
                        <i class="fas fa-desktop"></i>
                    </div>
                    <div class="metric-info">
                        <div class="metric-value" data-value="240">240</div>
                        <div class="metric-label">总资产数</div>
                        <div class="metric-change positive">
                            <i class="fas fa-arrow-up"></i> +12 本月
                        </div>
                    </div>
                </div>
                
                <div class="metric-card">
                    <div class="metric-icon" style="background: linear-gradient(135deg, ${this.colors.success}, #10b981);">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="metric-info">
                        <div class="metric-value" data-value="189">189</div>
                        <div class="metric-label">使用中</div>
                        <div class="metric-change positive">
                            <i class="fas fa-arrow-up"></i> 78.8%
                        </div>
                    </div>
                </div>
                
                <div class="metric-card">
                    <div class="metric-icon" style="background: linear-gradient(135deg, ${this.colors.warning}, #f59e0b);">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="metric-info">
                        <div class="metric-value" data-value="45">45</div>
                        <div class="metric-label">空闲资产</div>
                        <div class="metric-change negative">
                            <i class="fas fa-arrow-down"></i> -5 本周
                        </div>
                    </div>
                </div>
                
                <div class="metric-card">
                    <div class="metric-icon" style="background: linear-gradient(135deg, ${this.colors.danger}, #ef4444);">
                        <i class="fas fa-tools"></i>
                    </div>
                    <div class="metric-info">
                        <div class="metric-value" data-value="6">6</div>
                        <div class="metric-label">维修中</div>
                        <div class="metric-change neutral">
                            <i class="fas fa-minus"></i> 持平
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="utilization-chart">
                <h4>资产利用率趋势</h4>
                <div class="chart-container" id="utilization-trend"></div>
            </div>
        `;
        
        panel.innerHTML = content;
        this.createUtilizationChart();
    }

    createDepartmentInsightsPanel() {
        const panel = this.createPanel('dept-insights-panel', '🏢 部门洞察', 'success');
        
        const content = `
            <div class="insights-grid">
                <div class="insight-card">
                    <h4>📈 最活跃部门</h4>
                    <div class="dept-ranking">
                        <div class="ranking-item">
                            <span class="rank">1</span>
                            <span class="dept-name">IT部门</span>
                            <span class="dept-count">89</span>
                        </div>
                        <div class="ranking-item">
                            <span class="rank">2</span>
                            <span class="dept-name">销售部</span>
                            <span class="dept-count">45</span>
                        </div>
                        <div class="ranking-item">
                            <span class="rank">3</span>
                            <span class="dept-name">财务部</span>
                            <span class="dept-count">34</span>
                        </div>
                    </div>
                </div>
                
                <div class="insight-card">
                    <h4>💰 价值分布</h4>
                    <div class="value-distribution">
                        <div class="value-item">
                            <div class="value-bar">
                                <div class="value-fill" style="width: 45%; background: ${this.colors.primary};"></div>
                            </div>
                            <span>IT部门: ¥245万</span>
                        </div>
                        <div class="value-item">
                            <div class="value-bar">
                                <div class="value-fill" style="width: 25%; background: ${this.colors.success};"></div>
                            </div>
                            <span>销售部: ¥123万</span>
                        </div>
                        <div class="value-item">
                            <div class="value-bar">
                                <div class="value-fill" style="width: 20%; background: ${this.colors.warning};"></div>
                            </div>
                            <span>财务部: ¥89万</span>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        panel.innerHTML = content;
        this.animateValueBars();
    }

    createMaintenanceAnalyticsPanel() {
        const panel = this.createPanel('maintenance-panel', '🔧 维修分析', 'warning');
        
        const content = `
            <div class="maintenance-summary">
                <div class="summary-stats">
                    <div class="stat-item">
                        <span class="stat-value">28</span>
                        <span class="stat-label">本月维修</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-value">¥45K</span>
                        <span class="stat-label">维修费用</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-value">2.3天</span>
                        <span class="stat-label">平均周期</span>
                    </div>
                </div>
                
                <div class="maintenance-types">
                    <h4>维修类型分析</h4>
                    <div class="type-chart">
                        <div class="type-item">
                            <div class="type-indicator" style="background: ${this.colors.success};"></div>
                            <span class="type-name">预防性维修</span>
                            <span class="type-count">15</span>
                        </div>
                        <div class="type-item">
                            <div class="type-indicator" style="background: ${this.colors.warning};"></div>
                            <span class="type-name">纠正性维修</span>
                            <span class="type-count">8</span>
                        </div>
                        <div class="type-item">
                            <div class="type-indicator" style="background: ${this.colors.danger};"></div>
                            <span class="type-name">紧急维修</span>
                            <span class="type-count">3</span>
                        </div>
                        <div class="type-item">
                            <div class="type-indicator" style="background: ${this.colors.info};"></div>
                            <span class="type-name">升级改造</span>
                            <span class="type-count">2</span>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        panel.innerHTML = content;
    }

    createFinancialSummaryPanel() {
        const panel = this.createPanel('financial-panel', '💰 财务摘要', 'info');
        
        const content = `
            <div class="financial-overview">
                <div class="financial-metrics">
                    <div class="metric-large">
                        <span class="metric-value-large">¥1,100万</span>
                        <span class="metric-label-large">资产总值</span>
                        <div class="metric-trend">
                            <i class="fas fa-arrow-up" style="color: ${this.colors.success};"></i>
                            <span style="color: ${this.colors.success};">+8.5% 同比</span>
                        </div>
                    </div>
                    
                    <div class="financial-breakdown">
                        <div class="breakdown-item">
                            <span class="breakdown-label">本月新增</span>
                            <span class="breakdown-value" style="color: ${this.colors.success};">¥85万</span>
                        </div>
                        <div class="breakdown-item">
                            <span class="breakdown-label">折旧费用</span>
                            <span class="breakdown-value" style="color: ${this.colors.warning};">¥12万</span>
                        </div>
                        <div class="breakdown-item">
                            <span class="breakdown-label">维修支出</span>
                            <span class="breakdown-value" style="color: ${this.colors.danger};">¥4.5万</span>
                        </div>
                    </div>
                </div>
                
                <div class="roi-analysis">
                    <h4>投资回报分析</h4>
                    <div class="roi-chart">
                        <div class="roi-bar">
                            <div class="roi-fill" style="width: 85%; background: linear-gradient(90deg, ${this.colors.success}, ${this.colors.info});"></div>
                            <span class="roi-label">IT设备</span>
                            <span class="roi-value">85%</span>
                        </div>
                        <div class="roi-bar">
                            <div class="roi-fill" style="width: 72%; background: linear-gradient(90deg, ${this.colors.warning}, ${this.colors.success});"></div>
                            <span class="roi-label">办公设备</span>
                            <span class="roi-value">72%</span>
                        </div>
                        <div class="roi-bar">
                            <div class="roi-fill" style="width: 68%; background: linear-gradient(90deg, ${this.colors.info}, ${this.colors.primary});"></div>
                            <span class="roi-label">生产设备</span>
                            <span class="roi-value">68%</span>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        panel.innerHTML = content;
        this.animateROIBars();
    }

    createAlertsCenterPanel() {
        const panel = this.createPanel('alerts-panel', '🚨 警报中心', 'danger');
        
        const alerts = [
            { type: 'warning', message: '3台设备即将过保', time: '2小时前', priority: 'medium' },
            { type: 'danger', message: '1台服务器故障', time: '30分钟前', priority: 'high' },
            { type: 'info', message: '5台设备待维护', time: '1天前', priority: 'low' },
            { type: 'warning', message: '库存不足提醒', time: '3小时前', priority: 'medium' }
        ];
        
        const content = `
            <div class="alerts-container">
                <div class="alerts-summary">
                    <div class="alert-count high">2</div>
                    <div class="alert-count medium">3</div>
                    <div class="alert-count low">1</div>
                </div>
                
                <div class="alerts-list">
                    ${alerts.map(alert => `
                        <div class="alert-item ${alert.type} ${alert.priority}">
                            <div class="alert-icon">
                                <i class="fas fa-${alert.type === 'danger' ? 'exclamation-triangle' : 
                                                  alert.type === 'warning' ? 'exclamation-circle' : 'info-circle'}"></i>
                            </div>
                            <div class="alert-content">
                                <div class="alert-message">${alert.message}</div>
                                <div class="alert-time">${alert.time}</div>
                            </div>
                            <div class="alert-action">
                                <button class="alert-btn" onclick="assetDashboard.handleAlert('${alert.type}')">
                                    处理
                                </button>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
        
        panel.innerHTML = content;
    }

    createPanel(id, title, theme) {
        const panelsContainer = document.querySelector('.stats-grid');
        if (!panelsContainer) return null;
        
        const panel = document.createElement('div');
        panel.id = id;
        panel.className = `stats-card dashboard-panel ${theme}`;
        panel.innerHTML = `
            <div class="panel-header">
                <h3 class="panel-title">${title}</h3>
                <div class="panel-actions">
                    <button class="panel-btn" onclick="assetDashboard.refreshPanel('${id}')" title="刷新">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                    <button class="panel-btn" onclick="assetDashboard.expandPanel('${id}')" title="展开">
                        <i class="fas fa-expand-alt"></i>
                    </button>
                </div>
            </div>
            <div class="panel-content"></div>
        `;
        
        panelsContainer.appendChild(panel);
        return panel.querySelector('.panel-content');
    }

    createUtilizationChart() {
        const container = document.getElementById('utilization-trend');
        if (!container) return;

        const data = [82, 85, 78, 88, 92, 87, 90];
        const labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        
        const chartHTML = `
            <div class="mini-line-chart">
                ${data.map((value, index) => `
                    <div class="chart-point" style="
                        left: ${(index / (data.length - 1)) * 100}%;
                        bottom: ${value}%;
                        background: ${this.colors.primary};
                    " title="${labels[index]}: ${value}%"></div>
                `).join('')}
                <svg class="chart-line" viewBox="0 0 100 100" preserveAspectRatio="none">
                    <polyline points="${data.map((value, index) => 
                        `${(index / (data.length - 1)) * 100},${100 - value}`
                    ).join(' ')}" 
                    style="fill: none; stroke: ${this.colors.primary}; stroke-width: 2;" />
                </svg>
            </div>
        `;
        
        container.innerHTML = chartHTML;
    }

    animateValueBars() {
        setTimeout(() => {
            const bars = document.querySelectorAll('.value-fill');
            bars.forEach(bar => {
                const width = bar.style.width;
                bar.style.width = '0%';
                setTimeout(() => {
                    bar.style.transition = 'width 1s ease';
                    bar.style.width = width;
                }, 100);
            });
        }, 500);
    }

    animateROIBars() {
        setTimeout(() => {
            const bars = document.querySelectorAll('.roi-fill');
            bars.forEach((bar, index) => {
                const width = bar.style.width;
                bar.style.width = '0%';
                setTimeout(() => {
                    bar.style.transition = 'width 1.2s ease';
                    bar.style.width = width;
                }, index * 200);
            });
        }, 800);
    }

    startRealTimeUpdates() {
        // 每30秒更新一次数据
        setInterval(() => {
            this.updateRealTimeData();
        }, 30000);
    }

    updateRealTimeData() {
        // 模拟数据更新
        const metrics = document.querySelectorAll('.metric-value[data-value]');
        metrics.forEach(metric => {
            const currentValue = parseInt(metric.dataset.value);
            const variation = Math.floor(Math.random() * 5) - 2; // -2 到 +2 的变化
            const newValue = Math.max(0, currentValue + variation);
            
            metric.dataset.value = newValue;
            this.animateNumberChange(metric, newValue);
        });

        console.log('📊 仪表板数据已更新');
    }

    animateNumberChange(element, targetValue) {
        const currentValue = parseInt(element.textContent);
        const difference = targetValue - currentValue;
        const steps = 20;
        const stepValue = difference / steps;
        let currentStep = 0;

        const timer = setInterval(() => {
            currentStep++;
            const newValue = Math.floor(currentValue + stepValue * currentStep);
            element.textContent = newValue;

            if (currentStep >= steps) {
                clearInterval(timer);
                element.textContent = targetValue;
            }
        }, 50);
    }

    initializeInteractions() {
        // 添加面板悬停效果（在日志/模态上下文中抑制）
        const suppressed = this.isSuppressedContext();
        document.querySelectorAll('.dashboard-panel').forEach(panel => {
            panel.addEventListener('mouseenter', function() {
                if (suppressed) return;
                this.style.transform = 'translateY(-2px)';
                this.style.boxShadow = '0 8px 25px rgba(0,0,0,0.15)';
                this.style.willChange = 'transform, box-shadow';
            }, { passive: true });
            
            panel.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0)';
                this.style.boxShadow = '';
                this.style.willChange = '';
            }, { passive: true });
        });
    }

    refreshPanel(panelId) {
        console.log(`🔄 刷新面板: ${panelId}`);
        this.updateRealTimeData();
        window.advancedFeatures?.showNotification('面板刷新', '数据已更新', 'success');
    }

    expandPanel(panelId) {
        console.log(`🔍 展开面板: ${panelId}`);
        // 这里可以实现面板展开的详细视图
        window.advancedFeatures?.showNotification('面板展开', '详细视图已启用', 'info');
    }

    handleAlert(alertType) {
        console.log(`⚠️ 处理警报: ${alertType}`);
        window.advancedFeatures?.showNotification('警报处理', '警报已标记为已处理', 'success');
    }
}

// 自动初始化
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => {
        window.assetDashboard = new AssetDashboard();
        console.log('🏢 增强仪表板已启动');
    }, 3000);
});